#!/usr/bin/perl
#
# 文件版本修改功能
# 用法: chver.pl [version]
# 例如: chver.pl 1.2
#
# 当后面不跟参数时, 会自动读取现有版本并将次版本号增加1, 如1.2改为1.3
#

use strict;
use warnings;

my $blockFile = 'infoblock.h';

my ($majorVer, $minorVer);

# 从$blockFile文件里读取版本号
sub readVersion {
    my $filename = $blockFile;
    
    print "Reading version from '$filename' ...\n";

    open (IN, '<', $filename) or die "Can't open $filename: $!";
    while(<IN>) {
        if (/#define\s+APP_FW_VERSION_HIGH\s+(\d+)/) {
            $majorVer = $1;
        } elsif (/#define\s+APP_FW_VERSION_LOW\s+(\d+)/) {
            $minorVer = $1;
        }
    }
    close IN;
    
    print "    Version found: $majorVer.$minorVer\n";
    
    $minorVer++;
}

# 从字符串中分析版本号, "1.2.2"
sub extractVersionStr {
    my @ver = split /\D+/, shift;
    push @ver, 0 while @ver < 2;
    return @ver;
}

# 替换文件中的版本
sub processFile {
    my $filename = shift;
    
    print "Processing $filename ... ";

    open (IN, '<', $filename) or die "Can't open $filename: $!";
    my @lines = <IN>;
    close IN;

    my $replaced = 0;
    
    open (OUT, '>', $filename) or die $!;
    foreach(@lines) {
        if (s/(#define\s+APP_FW_VERSION_HIGH\s+)(\d+)/$1$majorVer/ ||
            s/(#define\s+APP_FW_VERSION_LOW\s+)(\d+)/$1$minorVer/) {
            ++$replaced;
        }
        
        print OUT $_;
    }
    close OUT;
    
    print $replaced == 2 ? "OK!" : "FAILED!", "\n";
}

# main

if ($#ARGV < 0) {
    readVersion;
} else {
    print "Extracting FileVersion from '$ARGV[0]' ...\n";
    ($majorVer, $minorVer) = extractVersionStr($ARGV[0]);
    print "    Version found: $majorVer.$minorVer\n";
}

print "Ready to process files\n";
print "    Version: $majorVer.$minorVer\n";

processFile $blockFile;
